import type { RouteRecordRaw } from 'vue-router'
import DefaultLayout from '@/layouts/Default.vue'
const modules = import.meta.glob('../views/**/*.vue')

/**
 * 菜单项类型定义
 */
export interface MenuItem {
    id: number
    name: string
    slug: string
    path: string
    meta?: any
    component: string
    icon?: string
    is_hidden: boolean
    children: MenuItem[]
}

/**
 * 从后端返回的菜单生成动态路由
 * @param menus 后端返回的菜单列表
 * @returns 动态路由列表
 */
export const generateRoutesFromMenus = (menus: MenuItem[]): RouteRecordRaw[] => {
    const routes: RouteRecordRaw[] = []

    menus.forEach((menu) => {
        if (menu.is_hidden) {
            // 跳过隐藏菜单
            return
        }

        const route: RouteRecordRaw = {
            path: menu.path,
            name: menu.slug,
            component: DefaultLayout, // 动态加载组件
            meta: menu.meta,
            children: []
        }

        if (menu.children.length === 0) {
            // 如果没有子菜单，则将当前菜单添加到路由列表中
            route!.children = [
                {
                    path: '/',
                    name: 'index',
                    component: getComponent(menu.component)
                }
            ]
        } else {
            route!.children = menu.children.map((child) => {
                return {
                    path: child.path,
                    name: child.slug,
                    component: getComponent(child.component),
                    meta: child.meta
                }
            })
        }

        routes.push(route)
    })

    return routes
}

// 定义一个工具函数，用于动态获取组件
function getComponent(path: string) {
    const fullPath = `../views/${path}.vue`
    if (modules[fullPath]) {
        return modules[fullPath] // 返回动态导入的组件函数
    } else {
        console.error(`Component not found: ${fullPath}`)
        // return null // 如果找不到路径，可以返回一个默认组件
        return modules['banner/Banner']
    }
}
